package com.example.qimo2;

import android.Manifest;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private FusedLocationProviderClient fusedLocationClient;
    private LocationCallback locationCallback;
    private Location lastLocation;
    private double totalDistance = 0;
    private boolean isTracking = false;

    private TextView distanceText;
    private Button startButton, stopButton, saveButton;
    private ListView recordsList;
    private ArrayList<String> records = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private long startTime, endTime;
    private static final String PREFS_NAME = "RunRecordsPrefs";
    private static final String RECORDS_KEY = "run_records";
    private SharedPreferences sharedPreferences;
    private Gson gson = new Gson();
    private Button checkInButton;
    private int consecutiveDays = 0;
    private String lastCheckInDate = "";
    private static final String CHECK_IN_PREFS = "CheckInPrefs";
    private static final String KEY_LAST_DATE = "last_date";
    private static final String KEY_CONSECUTIVE_DAYS = "consecutive_days";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkInButton = findViewById(R.id.checkInButton);
        loadCheckInStatus();
        updateCheckInButtonText();
        checkInButton.setOnClickListener(v -> handleCheckIn());

        sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        loadRecords();

        distanceText = findViewById(R.id.distanceText);
        startButton = findViewById(R.id.startButton);
        stopButton = findViewById(R.id.stopButton);
        saveButton = findViewById(R.id.saveButton);
        recordsList = findViewById(R.id.recordsList);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, records);
        recordsList.setAdapter(adapter);

        recordsList.setOnItemLongClickListener((parent, view, position, id) -> {
            new AlertDialog.Builder(this)
                    .setTitle("删除记录")
                    .setMessage("确定删除此条跑步记录吗？")
                    .setPositiveButton("删除", (dialog, which) -> {
                        records.remove(position);
                        adapter.notifyDataSetChanged();
                        saveRecords();
                        Toast.makeText(this, "记录已删除", Toast.LENGTH_SHORT).show();
                    })
                    .setNegativeButton("取消", null)
                    .show();
            return true;
        });

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult == null || !isTracking) return;

                Location newLocation = locationResult.getLastLocation();
                if (lastLocation != null) {
                    float distance = lastLocation.distanceTo(newLocation);
                    totalDistance += distance / 1000;
                    distanceText.setText(String.format(Locale.getDefault(), "%.2f 公里", totalDistance));
                }
                lastLocation = newLocation;
            }
        };

        startButton.setOnClickListener(v -> startTracking());
        stopButton.setOnClickListener(v -> stopTracking());
        saveButton.setOnClickListener(v -> saveRecord());
    }

    private void startTracking() {
        if (checkLocationPermission()) {
            isTracking = true;
            totalDistance = 0;
            distanceText.setText("0.00 公里");
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            saveButton.setEnabled(false);

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setInterval(5000);
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
            }
        }
        startTime = System.currentTimeMillis();
    }

    private void stopTracking() {
        isTracking = false;
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        saveButton.setEnabled(true);
        fusedLocationClient.removeLocationUpdates(locationCallback);
    }

    private void saveRecord() {
        endTime = System.currentTimeMillis();
        long duration = (endTime - startTime) / 1000;  // 秒数
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(new Date());
//        String record = time + " - " + String.format(Locale.getDefault(), "%.2f 公里", totalDistance);
        String record = time + " - " + String.format(Locale.getDefault(),
                "%.2f公里(用时%d分%d秒)", totalDistance, duration/60, duration%60);
        records.add(0, record);
        adapter.notifyDataSetChanged();
        saveButton.setEnabled(false);
        saveRecords();
        Toast.makeText(this, "记录已保存", Toast.LENGTH_SHORT).show();
    }
    private void loadRecords() {
        String json = sharedPreferences.getString(RECORDS_KEY, null);
        if (json != null) {
            Type type = new TypeToken<ArrayList<String>>() {}.getType();
            records = gson.fromJson(json, type);
            if (records == null) {
                records = new ArrayList<>();
            }
        }
    }
    private void saveRecords() {
        String json = gson.toJson(records);
        sharedPreferences.edit()
                .putString(RECORDS_KEY, json)
                .apply();
    }
    private void loadCheckInStatus() {
        SharedPreferences prefs = getSharedPreferences(CHECK_IN_PREFS, MODE_PRIVATE);
        lastCheckInDate = prefs.getString(KEY_LAST_DATE, "");
        consecutiveDays = prefs.getInt(KEY_CONSECUTIVE_DAYS, 0);
    }
    private void handleCheckIn() {
        String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

        if (today.equals(lastCheckInDate)) {
            Toast.makeText(this, "今天已经打卡过了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (isConsecutiveDay(today)) {
            consecutiveDays++;
        } else {
            consecutiveDays = 1;
        }

        lastCheckInDate = today;
        saveCheckInStatus();
        updateCheckInButtonText();
        Toast.makeText(this, "打卡成功！连续打卡 " + consecutiveDays + " 天", Toast.LENGTH_SHORT).show();
    }

    private boolean isConsecutiveDay(String today) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            Date lastDate = sdf.parse(lastCheckInDate);
            Date currentDate = sdf.parse(today);

            long diff = currentDate.getTime() - lastDate.getTime();
            return diff == 86400000; // 刚好相差1天（24*60*60*1000ms）
        } catch (Exception e) {
            return false;
        }
    }

    private void saveCheckInStatus() {
        getSharedPreferences(CHECK_IN_PREFS, MODE_PRIVATE)
                .edit()
                .putString(KEY_LAST_DATE, lastCheckInDate)
                .putInt(KEY_CONSECUTIVE_DAYS, consecutiveDays)
                .apply();
    }

    private void updateCheckInButtonText() {
        String text = (consecutiveDays > 0) ?
                "打卡（已连续" + consecutiveDays + "天）" : "每日打卡";
        checkInButton.setText(text);
    }

    private boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startTracking();
            } else {
                Toast.makeText(this, "需要位置权限才能记录跑步", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        fusedLocationClient.removeLocationUpdates(locationCallback);
    }
}